package primary.code03_Heap;

import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * 给定一个无序数组，每个元素距离排序后的位置的距离 <= K
 * 选择一种合适的排序方法，对该数据进行排序，复杂度为 (N-K) * O(logK)
 */
public class Code02_MoveDistanceSort {
    private static void moveDistanceSort(int[] arr, int dis) {
        PriorityQueue<Integer> heap = new PriorityQueue<Integer>((o1, o2) -> o1 - o2);//默认小根堆
        for (int i = 0; i <= dis; i++) {
            heap.add(arr[i]);
        }
        for (int i = dis + 1; i < arr.length; i++) {
            Integer poll = heap.poll();
            arr[i - dis - 1] = poll;
            heap.add(arr[i]);
        }
        for (int i = arr.length - 5; i <= arr.length - 1; i++) {
            arr[i] = heap.poll();
        }
    }

    //dis = 4
    private static void moveDistanceSortTest(int[] arr, int dis) {
        if (arr == null || arr.length <= 1) {
            return;
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(dis + 1);
        for (int i = 0; i <= dis; i++) {
            priorityQueue.add(arr[i]);
        }
        for (int i = 0; i < arr.length; i++) {
            arr[i] = priorityQueue.poll();
            if (i + dis + 1 < arr.length) {
                priorityQueue.add(arr[i + dis + 1]);
            }
        }
    }

    /*从大到小排序*/
    private static void moveDistanceReverseSort(int[] arr, int dis) {
        PriorityQueue<Integer> heap = new PriorityQueue<Integer>((o1, o2) -> o2 - o1);
        for (int i = 0; i <= dis; i++) {
            heap.add(arr[i]);
        }
        for (int i = dis + 1; i < arr.length; i++) {
            Integer poll = heap.poll();
            arr[i - dis - 1] = poll;
            heap.add(arr[i]);
        }
        for (int i = arr.length - 5; i <= arr.length - 1; i++) {
            arr[i] = heap.poll();
        }
    }

    public static void swap(int[] arr, int i, int j) {
        if (i == j) return;
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
    }

    public static void main(String[] args) {
        int[] arr = {4, 1, 1, 57, 23, 8, 23, 57, 87, 587, 89};
        moveDistanceSortTest(arr, 4);
//        for (int i = 0; i < arr.length / 2; i++) {
//            swap(arr, i, arr.length - i -1);
//        }
//        moveDistanceReverseSort(arr, 4);
        System.out.println(Arrays.toString(arr));
    }
}
